package com.winchain.chainbill.bill.biz.discount.rx;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.basic.activity.po.BasCpnRBiz;
import com.winchain.chainbill.basic.activity.po.BasCusCpn;
import com.winchain.chainbill.basic.activity.service.BasCpnRBizService;
import com.winchain.chainbill.basic.activity.service.BasCusCpnService;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillEvent;
import com.winchain.chainbill.bill.biz.transfer.vo.BillSplitEvent;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillDctRecoverCpnSubscriber extends OnErrorNotImplementedSubscriber<BillEvent<CbDct>> {
	@Autowired
	private BasCusCpnService basCusCpnService;
	@Autowired
	private BasCpnRBizService basCpnRBizService;

	public void onApplicationEvent(BillEvent<CbDct> t) {
		CbDct cbDct = (CbDct) t.getBill().getSource();
		if (((cbDct == null) || (cbDct.getDctId() == null)) && ((t instanceof BillSplitEvent))) {
			BillSplitEvent<CbDct> event = (BillSplitEvent) t;

			List<Bill<CbDct>> bills = (List<Bill<CbDct>>) event.getChildren();
			for (Bill<CbDct> bill : bills) {
				cbDct = (CbDct) bill.getSource();
				if ((cbDct != null) && (StringUtil.notEmpty(cbDct.getDctId()))) {
					break;
				}
			}
		}
		if ((cbDct == null) || (cbDct.getDctId() == null)) {
			return;
		}
		BasCpnRBiz bcb = new BasCpnRBiz();
		bcb.setBizId(cbDct.getDctId());
		List<BasCpnRBiz> bcbs = this.basCpnRBizService.selectByEntity(bcb);
		for (BasCpnRBiz basCpnRBiz : bcbs) {
			BasCusCpn bcc = (BasCusCpn) this.basCusCpnService.selectByKey(basCpnRBiz.getCusCpnId());
			String today = DateUtil.getSystemDate();
			if (today.compareTo(bcc.getEndDate()) > 0) {
				bcc.setCpnSts("0");
			} else {
				bcc.setCpnSts("1");
			}
			bcc.setUsedAmt(new BigDecimal(0));
			bcc.setUsedDate("");
			this.basCusCpnService.updateNotNull(bcc);
			this.basCpnRBizService.delete(basCpnRBiz);
		}
	}
}
